/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"context"
	"fmt"
	"github.com/docker/docker/client"
	"operator/cicd/runner"
	"operator/cicd/util"

	"github.com/spf13/cobra"
)

// buildCmd represents the build command
var buildCmd = &cobra.Command{
	Use:   "build",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		path, err := cmd.Flags().GetString("build_path")
		if err != nil {
			fmt.Println(err)
			return
		}
		cfg, err := util.LoadFromFile(path)
		if err != nil {
			fmt.Println("not found init file,use command init to create it")
			return
		}
		r := runner.NewGoRunner(cfg)
		err = r.BuildWithOpts()
		if err != nil {
			fmt.Println(err)
			return
		}
		c, err := client.NewClientWithOpts(client.WithHost(cfg.DockerConfig))
		if err != nil {
			fmt.Println(err)
			return
		}
		b := runner.NewBuilder(context.Background(), cfg, c)
		err = b.Run()
		if err != nil {
			return
		}
	},
}

func init() {
	rootCmd.AddCommand(buildCmd)
	buildCmd.Flags().StringP("build_path", "b", "./", "the build path")
}
